﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.Windows.Navigation;

namespace Nok_Air
{
    public partial class SelectFlightPage : PhoneApplicationPage
    {
        private string bookingNumberPar = "";
        private string lastNamePar = "";
        public SelectFlightPage()
        {
            InitializeComponent();
            DataContext = App.ViewModel;
        }

        private void FlightListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {          
            
            // If selected index is -1 (no selection) do nothing
            if (FlightListBox.SelectedIndex == -1)
                return;
            NavigationService.Navigate(new Uri("/CheckIn/3SelectPassengerPage.xaml?FlightIndex=" + FlightListBox.SelectedIndex + "&bookingNumber=" + bookingNumberPar, UriKind.Relative));

            // Reset selected index to -1 (no selection)
            FlightListBox.SelectedIndex = -1;
            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            progressbar.IsOpen = true;
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.TryGetValue("lastName", out lastNamePar) && NavigationContext.QueryString.TryGetValue("bookingNumber", out bookingNumberPar))
            {
                Nok_Air.WebService.NokAirServicesHelper nokSHelp = new Nok_Air.WebService.NokAirServicesHelper();
                nokSHelp.GetPassengersCompleted += (s, ev) => {
                    Dispatcher.BeginInvoke(() => {
                        if (ev.exception != null && NavigationService.CanGoBack)
                        {
                            MessageBox.Show(ev.exception.Message);
                            NavigationService.GoBack();
                        }
                        progressbar.IsOpen = false;
                    });
                };
                nokSHelp.GetPassengers(bookingNumberPar, lastNamePar);
            }
        }
    }
}
